﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SOLID五大设计原则
{
    // 高层模块
    public class UserService
    {
        private readonly ILogger _logger;
        private readonly IRepository<User> _repository;

        // 依赖注入
        public UserService(ILogger logger, IRepository<User> repository)
        {
            _logger = logger;
            _repository = repository;
        }

        public void RegisterUser(User user)
        {
            try
            {
                _repository.Save(user);
                _logger.Log($"用户 {user.Name} 注册成功");
            }
            catch (Exception ex)
            {
                _logger.Log($"注册失败: {ex.Message}");
            }
        }
    }

    // 抽象接口
    public interface ILogger
    {
        void Log(string message);
    }

    public interface IRepository<T>
    {
        void Save(T entity);
    }

    // 具体实现
    public class ConsoleLogger : ILogger
    {
        public void Log(string message) => Console.WriteLine(message);
    }

    public class FileLogger : ILogger
    {
        public void Log(string message) => File.AppendAllText("log.txt", message);
    }

    public class SqlRepository<T> : IRepository<T>
    {
        public void Save(T entity)
        {
            // 数据库保存逻辑
        }
    }

    public class User
    {
        public string Name { set; get; }
    }
}
